﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Hezi.BLL
{
    public class CacheManager
    {
        private static string RedisPath = System.Configuration.ConfigurationManager.AppSettings["redisAddress"];
        private ConnectionMultiplexer redis { get { return lazyConnection.Value; } }
        public IDatabase db;
        private static readonly TimeSpan expireTime = TimeSpan.FromDays(3);//设置公共过期时间
        public CacheManager()
        {
            //redis = ConnectionMultiplexer.Connect(RedisPath);//"localhost:6379,password=123456"
            //redis = ConnectionMultiplexer.Connect("139.196.90.111:6379,password=xiaofeng");
            db = redis.GetDatabase();
        }
        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(RedisPath);
        });
        public bool StringSet(string key,string value,int mill)
        {
            return db.StringSet(key, value,TimeSpan.FromMilliseconds(mill));
        }
        public string StringGet(string key)
        {
            return db.StringGet(key);
        }
        /// <summary>
        /// 写入缓存列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        public long ListSet<T>(string key, T t) where T : class
        {
            var r= db.ListRightPush(key, JsonConvert.SerializeObject(t));
            db.KeyExpire(key, expireTime);
            return r;
           //var c=  db.ListLength(key);
        }
        /// <summary>
        /// 获取缓存列表最左边数据,并从列表删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T ListGet<T>(string key) where T:class
        {
            string r= db.ListLeftPop(key);
            if (string.IsNullOrEmpty(r))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(r);
        }
        /// <summary>
        /// 列表中是否有数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ListHas(string key)
        {
            return db.ListLength(key)>0;
        }
        /// <summary>
        /// 哈希表中是否有指定数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool HashHasValue(string value)
        {
            return db.HashExists(ConfigKey.userKey, value);
        }
        /// <summary>
        /// 哈希表中添加数据,不过期
        /// </summary>
        /// <param name="value"></param>
        public void HashSetNotExpire(string value)
        {
            db.HashIncrement(ConfigKey.userKey, value);
        }
    }
}
